package cn.wit.summit.chwan.retrofit;

import org.greenrobot.eventbus.EventBus;

import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Alan on 2018/6/4.
 */

public abstract class MyCallback<T> implements Callback<T> {

    public abstract void onSuccess(T model);

    public abstract void onFailure(int code, String msg);

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (call.isCanceled()) return;
        if (response.isSuccessful()) {
            ResponseBase<T> responseBase = (ResponseBase<T>) response.body();
//            if (responseBase.getSucc()==0 || responseBase.getCode()!=600) {
            if (responseBase.getCode()!=600) {
                onFailure(responseBase.getCode(), responseBase.getMsg());
            } else {
                onSuccess(response.body());
            }
        } else {
//            onFailure(response.code(), response.errorBody().toString());
            int code = -3;
            String msg = "网络异常，请检查网络！";
            LogUtils.e("onResponse>>>>isSuccessful>>msg:"+msg);
            EventBus.getDefault().post(new NotNetEvent(false));
            onFailure(code, msg);
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (call.isCanceled()) return;
        int code = 0;
        String msg = t.getMessage();
        if (StringUtils.isEmpty(msg) || msg.contains("Failed to connect")|| msg.contains("failed to connect")
                || msg.contains("Unable to resolve")|| msg.contains("unexpected end of stream")) {
            code = -3;
            msg = "网络异常，请检查网络！";
            EventBus.getDefault().post(new NotNetEvent(false));
        }
        if (msg.contains("java.lang.IllegalStateException")) {
            code = -4;
            msg = "数据解析失败！";
        }
        onFailure(code, msg);
    }
}
